<template>
  <div class="results">
    <template v-if="showResults && sqlStatements.length > 0">
      <div class="success">
        <span><strong>解析成功！</strong> 共解析出 {{ totalCount }} 条SQL语句，显示 {{ sqlStatements.length }} 条</span>
        <button 
          class="format-toggle"
          :class="{ active: isFormatted }"
          @click="$emit('toggle-format')"
        >
          {{ isFormatted ? '已格式化' : '原始格式' }}
        </button>
      </div>
      
      <SqlItem
        v-for="(stmt, index) in sqlStatements"
        :key="index"
        :ref="`sqlItem${index}`"
        :statement="stmt"
        :index="index"
        :is-formatted="isFormatted"
      />
      
      <div class="stats">
        <div class="stat-item">
          <div class="stat-value">{{ sqlStatements.length }}</div>
          <div class="stat-label">SQL语句</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ totalParams }}</div>
          <div class="stat-label">参数总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ currentTime }}</div>
          <div class="stat-label">解析时间</div>
        </div>
      </div>
    </template>
    
    <div v-else style="text-align: center; color: #9ca3af; padding: 40px;">
      <p>请输入SQL日志并点击解析按钮</p>
    </div>
  </div>
</template>

<script>
import SqlItem from './SqlItem.vue'

export default {
  name: 'ResultsSection',
  components: {
    SqlItem
  },
  props: {
    sqlStatements: {
      type: Array,
      default: () => []
    },
    isFormatted: {
      type: Boolean,
      default: true
    },
    showResults: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      totalCount: 0,
      currentTime: new Date().toLocaleTimeString()
    }
  },
  computed: {
    totalParams() {
      return this.sqlStatements.reduce((sum, stmt) => sum + stmt.parameters.length, 0)
    }
  },
  watch: {
    sqlStatements() {
      this.currentTime = new Date().toLocaleTimeString()
      // 保存总数用于显示
      if (this.sqlStatements.length > 0) {
        this.totalCount = this.$parent.sqlStatements.length
      }
    }
  },
  methods: {
    // 获取查询结果数据用于ER图分析（支持所有SQL类型）
    getQueryResultsForEr() {
      const queryResults = []
      
      // 遍历所有SqlItem组件，获取查询结果
      this.sqlStatements.forEach((stmt, index) => {
        const sqlItem = this.$refs[`sqlItem${index}`]
        if (sqlItem && sqlItem[0]) { // Vue的ref在v-for中返回数组
          const result = sqlItem[0].getQueryResultForEr()
          if (result) {
            queryResults.push({
              sql: stmt.processed,
              type: this.getSQLType(stmt.processed),
              result: result
            })
          }
        }
      })
      
      console.log(`ResultsSection收集到 ${queryResults.length} 个查询结果`)
      return queryResults
    },
    
    // 获取SQL类型
    getSQLType(sql) {
      const upperSQL = sql.toUpperCase().trim()
      if (upperSQL.startsWith('SELECT')) return 'SELECT'
      if (upperSQL.startsWith('INSERT')) return 'INSERT'
      if (upperSQL.startsWith('UPDATE')) return 'UPDATE'
      if (upperSQL.startsWith('DELETE')) return 'DELETE'
      return 'OTHER'
    }
  }
}
</script>

<style scoped>
.results {
  min-height: 200px;
}

.success {
  background: #d1fae5;
  border: 1px solid #a7f3d0;
  color: #059669;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.format-toggle {
  background: white;
  color: #4f46e5;
  border: 2px solid #4f46e5;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.format-toggle:hover {
  background: #f3f4fe;
}

.format-toggle.active {
  background: #4f46e5;
  color: white;
}

.stats {
  display: flex;
  gap: 20px;
  margin-top: 30px;
  padding-top: 30px;
  border-top: 1px solid #e5e7eb;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 2em;
  font-weight: 700;
  color: #4f46e5;
  margin-bottom: 5px;
}

.stat-label {
  color: #6b7280;
  font-size: 0.9em;
}

@media (max-width: 768px) {
  .success {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .success span {
    margin-bottom: 8px;
  }
  
  .stats {
    flex-direction: column;
  }
}
</style>